package com.cus.tom.transfer.utils;

import static com.plata.base.aclr.utils.NetworkUtils.close;

import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Telephony;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.bean.Contractor;
import com.cus.tom.transfer.bean.FileType;
import com.cus.tom.transfer.bean.MediaData;
import com.cus.tom.transfer.bean.PhoneCall;
import com.cus.tom.transfer.bean.Sms;
import com.cus.tom.transfer.frag.BaseDialogFragment;
import com.cus.tom.transfer.frag.TipDlg;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.OnPermissionPageCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Read {

    public static void toRead(FragmentActivity activity, String msg, Runnable runnable) {
        if (!XXPermissions.isGranted(activity, Permission.MANAGE_EXTERNAL_STORAGE)) {
            TipDlg dlg = new TipDlg().setMsg(msg);
            dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                @Override
                public void onDismiss(boolean isOk, Object value) {
                    if (isOk) {
                        toSetting(activity, runnable, true, Permission.MANAGE_EXTERNAL_STORAGE);
                    } else {
                        runnable.run();
                    }
                }
            });
            dlg.show(activity.getSupportFragmentManager(), "");
        } else if (runnable != null) {
            runnable.run();
        }
    }

    public static boolean hasPermission(String permission) {
        return ContextCompat.checkSelfPermission(App.getApp(), permission) == PackageManager.PERMISSION_GRANTED;
    }

    public static void toSetting(FragmentActivity activity, Runnable runnable, boolean runWithoutPermission, String... permission) {
        XXPermissions.with(activity).permission(permission).request(new OnPermissionCallback() {
            @Override
            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                if (!allGranted && !runWithoutPermission) {
                    return;
                }
                if(runnable != null) {
                    runnable.run();
                }
            }

            @Override
            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                if (doNotAskAgain) {
                    TipDlg dlg = new TipDlg().setMsg("权限被永久拒绝，请手动授予权限");
                    dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                        @Override
                        public void onDismiss(boolean isOk, Object value) {
                            if (isOk) {
                                XXPermissions.startPermissionActivity(
                                        activity, permissions, new OnPermissionPageCallback() {
                                            @Override
                                            public void onGranted() {
                                                runnable.run();
                                            }

                                            @Override
                                            public void onDenied() {
                                                if (runWithoutPermission) {
                                                    runnable.run();
                                                }
                                            }
                                        });
                            } else if (runWithoutPermission) {
                                runnable.run();
                            }
                        }
                    });
                    dlg.show(activity.getSupportFragmentManager(), "");
                } else if (runWithoutPermission) {
                    runnable.run();
                }
            }
        });
    }


    boolean isLoadContinue;

    public List<MediaData> loadImageData(Context context, int page, int... pageSize) {
        String dirPathName = "";
        int pageSizeData = 50;
        if (pageSize.length > 0) {
            pageSizeData = pageSize[0];
        }

        List<MediaData> mediaDataList = new ArrayList<>();
        final String[] imageProjection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE, MediaStore.Images.Media.MIME_TYPE, MediaStore.Images.Media.DATE_ADDED, MediaStore.MediaColumns.WIDTH, MediaStore.MediaColumns.HEIGHT, MediaStore.MediaColumns.BUCKET_DISPLAY_NAME};
        String mImageSelection = MediaStore.Images.Media.DATA + " like?";
        String[] mImageSelectionArgs = new String[]{"%" + dirPathName + "%"};
        Cursor cursor = null;
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                Bundle bundle = new Bundle();
                bundle.putString(ContentResolver.QUERY_ARG_SQL_SELECTION, TextUtils.isEmpty(dirPathName) ? null : mImageSelection);
                bundle.putStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS, TextUtils.isEmpty(dirPathName) ? null : mImageSelectionArgs);
                bundle.putString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER, imageProjection[5] + " DESC");
                bundle.putInt(ContentResolver.QUERY_ARG_LIMIT, pageSizeData);
                bundle.putInt(ContentResolver.QUERY_ARG_OFFSET, page * pageSizeData);
                cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageProjection, bundle, null);
            } else {
                cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageProjection, TextUtils.isEmpty(dirPathName) ? null : mImageSelection, TextUtils.isEmpty(dirPathName) ? null : mImageSelectionArgs, imageProjection[5] + " DESC LIMIT " + page * pageSizeData + " , " + pageSizeData);
            }

        } catch (SecurityException e) {
            e.printStackTrace();
        }
        boolean hasItem = false;
        while (cursor != null && cursor.moveToNext()) {
            try {
                hasItem = true;
                int imgId = cursor.getInt(cursor.getColumnIndexOrThrow(imageProjection[0]));
                String imageName = cursor.getString(cursor.getColumnIndexOrThrow(imageProjection[1]));
                String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(imageProjection[2]));
                long imgSize = cursor.getLong(cursor.getColumnIndexOrThrow(imageProjection[3]));
                if (imgSize == 0) {
                    imgSize = new File(imagePath).length();
                }
                String imageMimeType = cursor.getString(cursor.getColumnIndexOrThrow(imageProjection[4]));
                long imageAddTime = cursor.getLong(cursor.getColumnIndexOrThrow(imageProjection[5]));
                if (imageAddTime == 0) {
                    imageAddTime = new File(imagePath).lastModified() / 1000;
                }
                int imageWidth = cursor.getInt(cursor.getColumnIndexOrThrow(imageProjection[6]));
                int imageHeight = cursor.getInt(cursor.getColumnIndexOrThrow(imageProjection[7]));

                Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imgId));

                if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)) {
                    if (TextUtils.isEmpty(imagePath)) {
                        continue;
                    }

                    File imageFile = new File(imagePath);
                    if (!imageFile.exists() || imageFile.length() <= 0) {
                        continue;
                    }
                }
                if (!HVEUtil.isLegalImage(imagePath)) {
                    isLoadContinue = true;
                    continue;
                }

                if (imageWidth == 0 || imageHeight == 0) {
                    BitmapFactory.Options options = BitmapDecodeUtils.getBitmapOptions(imagePath);
                    imageWidth = options.outWidth;
                    imageHeight = options.outHeight;
                }
                if (imageWidth == 0 || imageHeight == 0) {
                    isLoadContinue = true;
                    continue;
                }
                MediaData mediaData = MediaPickManager.getInstance().updateSelectMediaData(imagePath);
                if (mediaData != null) {
                    mediaData.setType(FileType.PIC.getCode());
                    mediaData.setDirName(dirPathName);
                    mediaDataList.add(mediaData);
                } else {
                    MediaData item = new MediaData();
                    item.setType(FileType.PIC.getCode());
                    item.setDirName(dirPathName);
                    item.setName(imageName);
                    item.setPath(imagePath);
                    item.setUri(uri);
                    item.setSize(imgSize);
                    item.setMimeType(imageMimeType);
                    item.setAddTime(imageAddTime);
                    item.setWidth(imageWidth);
                    item.setHeight(imageHeight);
                    mediaDataList.add(item);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        if (mediaDataList.isEmpty() && hasItem) {
            MediaData tmp = new MediaData();
            tmp.isValid = false;
        }
        return mediaDataList;
    }

    private static final int MAX_VIDEO_WIDTH = 4096;

    public List<MediaData> loadVideo(Context context, int page, int... pageSize) {
        String aDirName = "";
        int aPageSize = 50;
        if (pageSize.length > 0) {
            aPageSize = pageSize[0];
        }
        List<MediaData> videos = new ArrayList<>();
        final String[] videoProjections = {MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.MIME_TYPE, MediaStore.Video.Media.DATE_MODIFIED, MediaStore.Video.Media.DURATION, MediaStore.MediaColumns.WIDTH, MediaStore.MediaColumns.HEIGHT};

        String mVideoSelection = MediaStore.Video.Media.DATA + " like?";
        String[] mVideoSelectionArgs = new String[]{"%" + aDirName + "%"};
        Cursor cursor;
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                Bundle bundle = new Bundle();
                bundle.putString(ContentResolver.QUERY_ARG_SQL_SELECTION, TextUtils.isEmpty(aDirName) ? null : mVideoSelection);
                bundle.putStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS, TextUtils.isEmpty(aDirName) ? null : mVideoSelectionArgs);
                bundle.putString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER, videoProjections[5] + " DESC");
                bundle.putInt(ContentResolver.QUERY_ARG_LIMIT, aPageSize);
                bundle.putInt(ContentResolver.QUERY_ARG_OFFSET, page * aPageSize);
                cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoProjections, bundle, null);
            } else {
                cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoProjections, TextUtils.isEmpty(aDirName) ? null : mVideoSelection, TextUtils.isEmpty(aDirName) ? null : mVideoSelectionArgs, videoProjections[5] + " DESC LIMIT " + page * aPageSize + " , " + aPageSize);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return videos;
        }

        boolean hasItem = false;
        while (cursor != null && cursor.moveToNext()) {
            try {
                hasItem = true;
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(videoProjections[0]));
                String videoName = cursor.getString(cursor.getColumnIndexOrThrow(videoProjections[1]));
                String videoPath = cursor.getString(cursor.getColumnIndexOrThrow(videoProjections[2]));
                long videoSize = cursor.getLong(cursor.getColumnIndexOrThrow(videoProjections[3]));
                if (videoSize == 0) {
                    videoSize = new File(videoPath).length();
                }
                String videoMimeType = cursor.getString(cursor.getColumnIndexOrThrow(videoProjections[4]));
                long videoAddTime = cursor.getLong(cursor.getColumnIndexOrThrow(videoProjections[5]));
                if (videoAddTime == 0) {
                    videoAddTime = new File(videoPath).lastModified() / 1000;
                }
                long videoDuration = cursor.getInt(cursor.getColumnIndexOrThrow(videoProjections[6]));
                int videoWidth = cursor.getInt(cursor.getColumnIndexOrThrow(videoProjections[7]));
                int videoHeight = cursor.getInt(cursor.getColumnIndexOrThrow(videoProjections[8]));

                Uri uri = Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));

                if (!Utils.isVideoByPath(videoPath)) {
                    isLoadContinue = true;
                    continue;
                }

                if (videoDuration < 500) {
                    isLoadContinue = true;
                    continue;
                }

                if (videoWidth > MAX_VIDEO_WIDTH || videoHeight > MAX_VIDEO_WIDTH) {
                    isLoadContinue = true;
                    continue;
                }

                if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)) {
                    if (TextUtils.isEmpty(videoPath)) {
                        isLoadContinue = true;
                        continue;
                    }

                    File file = new File(videoPath);
                    if (!file.exists() || file.length() <= 0) {
                        isLoadContinue = true;
                        continue;
                    }
                }
                MediaData mediaData = MediaPickManager.getInstance().updateSelectMediaData(videoPath);
                if (mediaData != null) {
                    mediaData.setType(FileType.VIDEO.getCode());
                    mediaData.setDirName(aDirName);
                    videos.add(mediaData);
                } else {
                    MediaData item = new MediaData();
                    item.setType(FileType.VIDEO.getCode());
                    item.setDirName(aDirName);
                    item.setName(videoName);
                    item.setPath(videoPath);
                    item.setUri(uri);
                    item.setSize(videoSize);
                    item.setMimeType(videoMimeType);
                    item.setAddTime(videoAddTime);
                    item.setDuration(videoDuration);
                    item.setWidth(videoWidth);
                    item.setHeight(videoHeight);
                    videos.add(item);
                }
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        if (videos.isEmpty() && hasItem) {
            MediaData tmp = new MediaData();
            tmp.isValid = false;
            videos.add(tmp);
        }
        return videos;
    }

    public List<MediaData> loadAudio(Context context, int page, int... pageSize) {
        String aDirName = "";
        int aPageSize = 50;
        if (pageSize.length > 0) {
            aPageSize = pageSize[0];
        }
        List<MediaData> videos = new ArrayList<>();
        final String[] videoProjections = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.SIZE, MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.DATE_MODIFIED, MediaStore.Audio.Media.DURATION};

        String mVideoSelection = MediaStore.Audio.Media.DATA + " like?";
        String[] mVideoSelectionArgs = new String[]{"%" + aDirName + "%"};
        Cursor cursor;
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
                Bundle bundle = new Bundle();
                bundle.putString(ContentResolver.QUERY_ARG_SQL_SELECTION, TextUtils.isEmpty(aDirName) ? null : mVideoSelection);
                bundle.putStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS, TextUtils.isEmpty(aDirName) ? null : mVideoSelectionArgs);
                bundle.putString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER, videoProjections[5] + " DESC");
                bundle.putInt(ContentResolver.QUERY_ARG_LIMIT, aPageSize);
                bundle.putInt(ContentResolver.QUERY_ARG_OFFSET, page * aPageSize);
                cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, videoProjections, bundle, null);
            } else {
                cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, videoProjections, TextUtils.isEmpty(aDirName) ? null : mVideoSelection, TextUtils.isEmpty(aDirName) ? null : mVideoSelectionArgs, videoProjections[5] + " DESC LIMIT " + page * aPageSize + " , " + aPageSize);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return videos;
        }

        boolean hasItem = false;
        while (cursor != null && cursor.moveToNext()) {
            try {
                hasItem = true;
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(videoProjections[0]));
                String videoName = cursor.getString(cursor.getColumnIndexOrThrow(videoProjections[1]));
                String videoPath = cursor.getString(cursor.getColumnIndexOrThrow(videoProjections[2]));
                long videoSize = cursor.getLong(cursor.getColumnIndexOrThrow(videoProjections[3]));
                if (videoSize == 0) {
                    videoSize = new File(videoPath).length();
                }
                String videoMimeType = cursor.getString(cursor.getColumnIndexOrThrow(videoProjections[4]));
                long videoAddTime = cursor.getLong(cursor.getColumnIndexOrThrow(videoProjections[5]));
                if (videoAddTime == 0) {
                    videoAddTime = new File(videoPath).lastModified() / 1000;
                }
                long videoDuration = cursor.getInt(cursor.getColumnIndexOrThrow(videoProjections[6]));

                Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));

//                if (!Utils.isVideoByPath(videoPath)) {
//                    isLoadContinue = true;
//                    continue;
//                }
//
//                if (videoDuration < 500) {
//                    isLoadContinue = true;
//                    continue;
//                }
//
//                if (videoWidth > MAX_VIDEO_WIDTH || videoHeight > MAX_VIDEO_WIDTH) {
//                    isLoadContinue = true;
//                    continue;
//                }

                if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)) {
                    if (TextUtils.isEmpty(videoPath)) {
                        isLoadContinue = true;
                        continue;
                    }

                    File file = new File(videoPath);
                    if (!file.exists() || file.length() <= 0) {
                        isLoadContinue = true;
                        continue;
                    }
                }
                MediaData mediaData = MediaPickManager.getInstance().updateSelectMediaData(videoPath);
                if (mediaData != null) {
                    mediaData.setDirName(aDirName);
                    mediaData.setType(FileType.AUDIO.getCode());
                    videos.add(mediaData);
                } else {
                    MediaData item = new MediaData();
                    item.setType(FileType.AUDIO.getCode());
                    item.setDirName(aDirName);
                    item.setName(videoName);
                    item.setPath(videoPath);
                    item.setUri(uri);
                    item.setSize(videoSize);
                    item.setMimeType(videoMimeType);
                    item.setAddTime(videoAddTime);
                    item.setDuration(videoDuration);
                    videos.add(item);
                }
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        if (videos.isEmpty() && hasItem) {
            MediaData tmp = new MediaData();
            tmp.isValid = false;
            videos.add(tmp);
        }
        return videos;
    }

    public List<Contractor> getContract() {
        List<Contractor> list = new LinkedList<>();
        Cursor cursor = null;
        try {
            cursor = App.getApp().getContentResolver().query(
                    ContactsContract.Contacts.CONTENT_URI,
                    new String[]{ContactsContract.Contacts.LAST_TIME_CONTACTED,
                            ContactsContract.Contacts.DISPLAY_NAME,
                            ContactsContract.Contacts.TIMES_CONTACTED,
                            ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP,
                            ContactsContract.Contacts._ID},
                    null, null, null);
            while (cursor.moveToNext()) {
                try {
                    Contractor item = new Contractor();
                    int i = cursor.getColumnIndex(ContactsContract.Contacts.LAST_TIME_CONTACTED);
                    if (i >= 0) {
                        item.last_time_contacted = cursor.getLong(i);
                    }
                    i = cursor.getColumnIndex
                            (ContactsContract.Contacts.DISPLAY_NAME);
                    if (i >= 0) {
                        item.name = cursor.getString(i);
                    }
                    i = cursor.getColumnIndex
                            (ContactsContract.Contacts.TIMES_CONTACTED);
                    if (i >= 0) {
                        item.times_contacted = cursor.getString(i);
                    }
                    item.up_time = System.currentTimeMillis();
                    i = cursor.getColumnIndex
                            (ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP);
                    if (i >= 0) {
                        item.lastUsedTime = cursor.getLong(i);
                    }
                    i = cursor.getColumnIndex(ContactsContract.Contacts._ID);
                    if (i >= 0) {
                        String id = cursor.getString(i);
                        item.group = getContractGroup(id);

                        Cursor phones = App.getApp().getContentResolver().query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,
                                null, null);
                        if (phones.moveToFirst()) {
                            item.number = phones.getString(0);
                        }
                        phones.close();
                    }
                    item.source = "device";
                    list.add(item);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(cursor);
        }
        List<Contractor> tmp = getSim("content://icc/adn");
        if (tmp == null) {
            return list;
        } else if (tmp.isEmpty()) {
            tmp = getSim("content://icc/adn/subId/0");
        } else {
            list.addAll(tmp);
            return list;
        }

        if (tmp == null) {
            return list;
        } else if (tmp.isEmpty()) {
            tmp = getSim("content://icc/adn/subId/1");
        } else {
            list.addAll(tmp);
            return list;
        }

        if (tmp != null && !tmp.isEmpty()) {
            list.addAll(tmp);
        }
        return list;
    }

    private List getContractGroup(String id) {
        ArrayList list = new ArrayList();
        final String[] GROUP_PROJECTION = new String[]{
                ContactsContract.Groups._ID, ContactsContract.Groups.TITLE};

        Cursor cursor = App.getApp().getContentResolver().query(
                ContactsContract.Groups.CONTENT_URI,
                GROUP_PROJECTION,
                ContactsContract.Groups._ID + "=" + id,
                null, null);
        while (cursor.moveToNext()) {
            list.add(cursor.getString(0));
        }
        cursor.close();
        return list;
    }

    private List<Contractor> getSim(String path) {
        TelephonyManager telephonyManager = (TelephonyManager) App.getApp().getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager.getSimState() != TelephonyManager.SIM_STATE_READY) {
            return null;
        }
        List list = new LinkedList();
        Cursor mCursor = null;
        try {
            mCursor = App.getApp().getContentResolver().query(Uri.parse(path), null, null, null, null);
            if (mCursor == null) {
                return list;
            }
            if (mCursor != null) {
                while (mCursor.moveToNext()) {
                    try {
                        Contractor item = new Contractor();
                        // 取得联系人名字
                        int nameFieldColumnIndex = mCursor.getColumnIndex("name");
                        item.name = mCursor.getString(nameFieldColumnIndex);
                        // 取得电话号码
                        int numberFieldColumnIndex = mCursor
                                .getColumnIndex("number");
                        item.number = mCursor.getString(numberFieldColumnIndex);
                        item.source = "sim";
                        list.add(item);
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
            }
            mCursor.close();
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            close(mCursor);
        }
        return list;
    }


    public List<Sms> getAllSms() {
        List<Sms> list = new LinkedList<>();
        Cursor cursor = null;
        try {
            cursor = App.getApp().getContentResolver().query(Telephony.Sms.CONTENT_URI,
                    null, null, null, null);
            if (cursor == null) {
                return list;
            }
            while (cursor.moveToNext()) {
                try {
                    Sms item = new Sms();
                    int i = cursor.getColumnIndex(Telephony.Sms.TYPE);
                    if (i >= 0) {
                        item.type = cursor.getInt(i);
                    }
                    i = cursor.getColumnIndex(Telephony.Sms.DATE_SENT);
                    if (i >= 0) {
                        item.dateSent = cursor.getLong(i);
                    }
                    i = cursor.getColumnIndex(Telephony.Sms.DATE);
                    if (i >= 0) {
                        item.time = cursor.getLong(i);
                    }
                    i = cursor.getColumnIndex(Telephony.Sms.READ);
                    if (i >= 0) {
                        item.read = cursor.getInt(i);
                    }
                    i = cursor.getColumnIndex(Telephony.Sms.SEEN);
                    if (i >= 0) {
                        item.seen = cursor.getInt(i);
                    }
                    i = cursor.getColumnIndex(Telephony.Sms.BODY);
                    if (i >= 0) {
                        item.content = cursor.getString(i);
                    }
                    i = cursor.getColumnIndex(Telephony.Sms._ID);
                    if (i >= 0) {
                        item.id = cursor.getInt(i);
                    }
                    i = cursor.getColumnIndex(Telephony.Sms.STATUS);
                    if (i >= 0) {
                        item.status = cursor.getInt(i);
                    }
                    i = cursor.getColumnIndex(Telephony.Sms.PERSON);
                    if (i >= 0) {
                        item.person = cursor.getInt(i);
                    }
                    i = cursor.getColumnIndex(Telephony.Sms.ADDRESS);
                    if (i >= 0) {
                        item.phone = cursor.getString(i);
                    }
                    list.add(item);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            close(cursor);
        }
        return list;
    }

    public List<PhoneCall> getCalls() {
        List<PhoneCall> list = new LinkedList<>();
        String[] columns = {
                CallLog.Calls._ID
                , CallLog.Calls.NEW
                , CallLog.Calls.CACHED_NAME// 通话记录的联系人
                , CallLog.Calls.NUMBER// 通话记录的电话号码
                , CallLog.Calls.DATE// 通话记录的日期
                , CallLog.Calls.DURATION// 通话时长
                , CallLog.Calls.TYPE};// 通话类型}

        Cursor cursor = null;
        try {
            cursor = App.getApp().getContentResolver().query(CallLog.Calls.CONTENT_URI, // 查询通话记录的URI
                    columns
                    , null, null, CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示
            );
            while (cursor.moveToNext()) {
                try {
                    PhoneCall item = new PhoneCall();
                    int i = cursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
                    if (i >= 0) {
                        item.name = cursor.getString(i);  //姓名
                    }
                    i = cursor.getColumnIndex(CallLog.Calls.NUMBER);
                    if (i >= 0) {
                        item.number = cursor.getString(i);  //号码
                    }
                    if (TextUtils.isEmpty(item.name)) {
                        item.name = item.number;
                    }
                    i = cursor.getColumnIndex(CallLog.Calls.DATE);
                    if (i >= 0) {
                        item.date = cursor.getLong(i); //获取通话日期
                    }
                    i = cursor.getColumnIndex(CallLog.Calls.DURATION);
                    if (i >= 0) {
                        item.duration = cursor.getLong(i);//获取通话时长，值为多少秒
                    }
                    i = cursor.getColumnIndex(CallLog.Calls.TYPE);
                    if (i >= 0) {
                        item.type = cursor.getInt(i); //获取通话类型：1.呼入2.呼出3.未接
                    }
                    i = cursor.getColumnIndex(CallLog.Calls.NEW);
                    if (i >= 0) {
                        item.turnOn = cursor.getInt(i);
                    }
                    i = cursor.getColumnIndex(CallLog.Calls._ID);
                    if (i >= 0) {
                        item.id = cursor.getInt(i);
                    }
                    list.add(item);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            close(cursor);
        }
        return list;
    }

    public List<ApplicationInfo> loadApps() {
        if (!XXPermissions.isGranted(App.getApp(), Permission.MANAGE_EXTERNAL_STORAGE)) {
            return Collections.emptyList();
        }
        List<ApplicationInfo> allApps = App.getApp().getPackageManager().getInstalledApplications(0);
        Iterator<ApplicationInfo> it = allApps.iterator();
        while (it.hasNext()) {
            ApplicationInfo ai = it.next();
            if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                it.remove();
            }
        }
        return allApps;
    }

    public static String getWifiId(Context context) {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null || !wifiManager.isWifiEnabled()) {
            return null;
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String tmp = wifiInfo.getSSID();
        return tmp;
    }
}
